﻿using System.Security.Principal;
using System.Web;
using IterationLife.System.Tools;
using Microsoft.Ajax.Utilities;
using Util;
using Util.Domains.Contexts;
using Util.Helpers;
using Util.Security;
using Util.Webs.Security;

namespace IterationLife.Mobile.CampusFootball.Student.ApiGateway.Authentication {
    /// <summary>
    /// 身份认证模块
    /// </summary>
    public class AuthenticationModule : AuthenticateModuleBase {

        /// <summary>
        /// 获取安全令牌名称
        /// </summary>
        protected override string GetTokenName() {
            return "Authorization";
        }

        /// <summary>
        /// 通过安全令牌获取用户编号
        /// </summary>
        /// <param name="application">Http应用程序</param>
        /// <param name="token">安全令牌</param>
        protected override IPrincipal GetPrincipalByToken( HttpApplication application, string token )
        {
            if(!AuthenticationTokenHelper.IsTokenValid(token))
                return UnauthenticatedPrincipal.Instance;
            string userId = AuthenticationTokenHelper.GetUserIdByToken(token);
            if (userId.IsNullOrWhiteSpace())
                return UnauthenticatedPrincipal.Instance;
            return GetPrincipal(userId);
        }

        /// <summary>
        /// 创建应用程序上下文
        /// </summary>
        /// <param name="userId">用户编号</param>
        protected override IUserContext CreateUserContext( string userId ) {
            if( userId.IsEmpty() )
                return NullUserContext.Instance;
            UserContext result = new UserContext( true, userId, Net.Ip, Net.Host, Net.Browser );
            return result;
        }



    }
}
